package com.lin.forum.exception;

import com.lin.forum.common.Result;
import com.lin.forum.common.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    //处理 @RequestBody 参数校验异常
    //@ExceptionHandler 用于处理控制器抛出的异常
    @ResponseBody
    @ExceptionHandler(ApplicationException.class)
    public Result applicationExceptionHandler(ApplicationException e){
        e.printStackTrace();
        log.error("applicationException:"+e.getMessage());
        if(e.getErrorResult()!=null){
            return e.getErrorResult();
        }
        if(e.getMessage()==null||e.getMessage().equals("")){
            return Result.fail(ResultCodeEnum.ERROR_SERVICES);//服务器内部错误
        }
        //返回具体的错误信息
        return Result.fail(e.getMessage());
    }
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e){
        e.printStackTrace();
        log.error("exceptionHandler:"+e.getMessage());
        if(e.getMessage()==null||e.getMessage().equals("")){
            return Result.fail(ResultCodeEnum.ERROR_SERVICES);//服务器内部错误
        }
        //返回具体的错误信息
        return Result.fail(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(IllegalArgumentException.class)
    public Result IllegalArgumentExceptionHandler(IllegalArgumentException e){
//        e.printStackTrace();
        log.error("exceptionHandler:"+e.getMessage());
        if(e.getMessage()==null||e.getMessage().equals("")){
            return Result.fail(ResultCodeEnum.ERROR_SERVICES);//服务器内部错误
        }
        //返回具体的错误信息
        return Result.fail("JWT token不能为空");
    }
}
